﻿using System.Text;

namespace DACU.Tools
{
	class UrlDecoder
	{
		// Fields
		private int _bufferSize;
		private byte[] _byteBuffer;
		private char[] _charBuffer;
		private Encoding _encoding;
		private int _numBytes;
		private int _numChars;

		// Methods
		internal UrlDecoder(int bufferSize, Encoding encoding)
		{
			_bufferSize = bufferSize;
			_encoding = encoding;
			_charBuffer = new char[bufferSize];
		}

		internal void AddByte(byte b)
		{
			if (_byteBuffer == null)
				_byteBuffer = new byte[_bufferSize];
			_byteBuffer[_numBytes++] = b;
		}

		internal void AddChar(char ch)
		{
			if (_numBytes > 0)
				FlushBytes();
			_charBuffer[_numChars++] = ch;
		}

		private void FlushBytes()
		{
			if (_numBytes > 0)
			{
				_numChars += _encoding.GetChars(_byteBuffer, 0, _numBytes, _charBuffer, _numChars);
				_numBytes = 0;
			}
		}

		internal string GetString()
		{
			if (_numBytes > 0)
				FlushBytes();
			return _numChars > 0 ? new string(_charBuffer, 0, _numChars) : string.Empty;
		}
	}
}
